package com.decade.qiyeshapan.aspect;

import cn.hutool.json.JSONUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LoggingAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void controller() {}

    @Before("controller()")
    public void logBefore(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        String[] argsStrings = new String[args.length];
        for (int i = 0; i < args.length; i++) {
            try {
                argsStrings[i] = args[i] != null ? JSONUtil.toJsonStr(args[i]) : "null";
            } catch (Exception e) {
                argsStrings[i] = args[i] != null ? args[i].toString() : "null";
            }
        }
        
//        logger.info("Entering in Method :  " + joinPoint.getSignature().getName());
//        logger.info("Class Name :  " + joinPoint.getSignature().getDeclaringTypeName());
        logger.info("Arguments : \n" + String.join("\n", argsStrings));
//        logger.info("Target class : " + joinPoint.getTarget().getClass().getName());
    }

    @AfterReturning(pointcut = "controller()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        String jsonResult = JSONUtil.toJsonStr(result);
        logger.info("Method Return value : " + jsonResult);
    }
} 